﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using Assessment.Management.SharedComponent.Params.MenuManagers;
using Assessment.Management.SharedComponent.Entities;
using Assessment.Management.SharedComponent.Constants;
using Assessment.Management.BIZ;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace Assessment.Management.UI.Admin
{
    public partial class SentMail : System.Web.UI.Page
    {
        private List<string> lstAtt = new List<string>();
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        private bool ValidateDataToAdd()
        {
            bool kt = true;

            if (txtReceive.Text == "" || txtUserName.Text == "")
            {
                kt = false;
            }
            return kt;
        }
        public static bool IsEmail(string str)
        {
            string strRegex = (@"\S+@\S+\.\S+");
            Regex regex = new Regex(strRegex);
            Match match = regex.Match(str);
            if (match.Success)
                return true;
            else
            { 
                return false;
            }
        }

        public static string DecryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            // Step 1. Bam chuoi su dung MD5
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
            // Step 2. Tao doi tuong TripleDESCryptoServiceProvider moi
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            // Step 3. Cai dat bo giai ma
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            // Step 4. Convert chuoi (Message) thanh dang byte[]
            byte[] DataToDecrypt = Convert.FromBase64String(Message);
            // Step 5. Bat dau giai ma chuoi
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                // Xoa moi thong tin ve Triple DES va HashProvider de dam bao an toan
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            // Step 6. Tra ve ket qua bang dinh dang UTF8
            return UTF8.GetString(Results);
        }
        //Hàm mã hóa chuỗi
        public static string EncryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            // Buoc 1: Bam chuoi su dung MD5
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
            // Step 2. Tao doi tuong TripleDESCryptoServiceProvider moi
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            // Step 3. Cai dat bo ma hoa
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            // Step 4. Convert chuoi (Message) thanh dang byte[]
            byte[] DataToEncrypt = UTF8.GetBytes(Message);
            // Step 5. Ma hoa chuoi
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                // Xoa moi thong tin ve Triple DES va HashProvider de dam bao an toan
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            // Step 6. Tra ve chuoi da ma hoa bang thuat toan Base64
            return Convert.ToBase64String(Results);
        }
        protected void btnSent_Click(object sender, EventArgs e)
        {
            if (ValidateDataToAdd())
            {
                if (!IsEmail(txtReceive.Text))
                {
                    lblMessage.Text = "<font color='Red'>Email không hợp lệ</font>";
                }
                else
                {
                    AccountParam param = new AccountParam(FunctionType.GetAccount);
                    Account acc = new Account();
                    acc.Username = txtUserName.Text;
                    acc.Email = txtReceive.Text;
                    param.Account = acc;
                    MainController.Provider.Execute(param);
                    string s = DateTime.Now.ToString();
                    string[] a = s.Split(' ');
                    string[] b = a[1].Split(':');
                    string[] c = a[0].Split('/');
                    string passnew = c[0] + c[1] + c[2] + b[0] + b[1] + b[2];
                   // param.Account.Username = param.Account.Username;
                    param.Account.Password = EncryptString(passnew, "123");
                    //param.Account.UpdatedBy = SMX.smx_UpdatedBy;
                    //param.Account.UpdatedDTG = DateTime.Now;
                    AccountParam param2 = new AccountParam(FunctionType.UpdateAccount);
                    param2.Account = param.Account;
                    MainController.Provider.Execute(param2);
                    string Pass = DecryptString(param.Account.Password, "123");
                    SmtpClient client = new SmtpClient();
                    client = new SmtpClient("smtp.gmail.com", 587);
                    client.Credentials = new System.Net.NetworkCredential("linhtk84@gmail.com", "linhh123");
                    client.EnableSsl = true;

                    MailMessage mail = new MailMessage("linhtk84@gmail.com", txtReceive.Text.Trim(), "Khôi phục mật khẩu", "Mật khẩu mới của bạn là: " + Pass);
                    if (lstAtt != null)
                    {
                        foreach (string file in lstAtt)
                        {
                            mail.Attachments.Add(new Attachment(file));
                        }
                    }

                    client.Send(mail);
                    lblMessage.Text = "<font color='Red'>Mật khẩu mới của bạn đã được gửi vào địa chỉ Email: " + txtReceive.Text + "</font>";

                }
            }
            else
            {
                lblMessage.Text = "<font color='Red'>Thông tin chưa đầy đủ. Vui lòng kiểm tra lại</font>";
            }
        }

    }
}